package com.heima.comment.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.heima.api.IAuthClient;
import com.heima.comment.service.CommentRepayService;
import com.heima.comment.user.dtos.ApCommentRepayLikeDto;
import com.heima.comment.user.dtos.ApCommentRepaySaveDto;
import com.heima.comment.user.dtos.ApCommentRepaySearchDto;
import com.heima.comment.user.pojos.ApComment;
import com.heima.comment.user.pojos.ApCommentIsLike;
import com.heima.comment.user.pojos.ApCommentRepay;
import com.heima.comment.user.pojos.ApCommentRepayIsLike;
import com.heima.comment.user.vos.ApCommentRepaySearchVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.CommentThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;


@Service
@RequiredArgsConstructor
public class CommentRepayServiceImpl implements CommentRepayService {

    private final IAuthClient iAuthClient;
    private final MongoTemplate mongoTemplate;
    private final static Integer DEFAULT_LIKES = 0;
    private final static Integer DEFAULT_SIZE = 10;
    private final static Long ABNORMAL_TIME = 20000000000000L;
    private final static Integer LIKE_STATUS = 0;
    private final static Integer UNLOGIN_USERID = 0;

    /**
     * 评论回复保存
     * @param saveDto
     * @return
     */
    @Override
    public ResponseResult commentRepaySave(ApCommentRepaySaveDto saveDto) {
        //判断用户是否登录
        Integer id = CommentThreadLocalUtil.getUser().getId();
        if(id == UNLOGIN_USERID){
            return ResponseResult.errorResult(AppHttpCodeEnum.USER_UNLOGIN,"用户未登录！");
        }

        ApCommentRepay apCommentRepay = new ApCommentRepay();
        BeanUtils.copyProperties(saveDto,apCommentRepay);
        apCommentRepay.setCommentRepayId(UUID.randomUUID().toString());
        apCommentRepay.setLikes(DEFAULT_LIKES);
        long nowTime = System.currentTimeMillis();
        apCommentRepay.setCreatedTime(nowTime);

        //通过feign请求获取当前用户信息
        String name = iAuthClient.getName(id);

        apCommentRepay.setAuthorId(id);
        apCommentRepay.setAuthorName(name);

        mongoTemplate.save(apCommentRepay);

        //更新评论数量
        ApComment apComment = mongoTemplate.findById(saveDto.getCommentId(), ApComment.class);
        apComment.setReply(apComment.getReply()+1);
        mongoTemplate.save(apComment);

        return ResponseResult.okResult(null);
    }

    /**
     * 查询评论回复列表
     * @param searchDto
     * @return
     */
    @Override
    public ResponseResult commentRepaySearch(ApCommentRepaySearchDto searchDto) {
        Integer userId = CommentThreadLocalUtil.getUser().getId();

        long minDate = searchDto.getMinDate().getTime();

        Query query = new Query();
        query.addCriteria(Criteria.where("commentId").is(searchDto.getCommentId()));
        if(minDate != ABNORMAL_TIME){
            query.addCriteria(Criteria.where("createdTime").gt(minDate));
        }
        query.limit(DEFAULT_SIZE);
        List<ApCommentRepay> commentRepayList = mongoTemplate.find(query, ApCommentRepay.class);

        List<ApCommentRepaySearchVo> commentListVos = new ArrayList<>();

        //判断用户是否点赞当前评论
        commentRepayList.stream().map(apComment ->{
            ApCommentRepaySearchVo apCommentRepaySearchVo = new ApCommentRepaySearchVo();
            BeanUtils.copyProperties(apComment,apCommentRepaySearchVo);
            apCommentRepaySearchVo.setId(apComment.getCommentRepayId());
            String id = apComment.getCommentRepayId();
            ApCommentRepayIsLike apCommentRepayIsLike = mongoTemplate.findById(id, ApCommentRepayIsLike.class);
            if(ObjectUtils.isNotEmpty(apCommentRepayIsLike) && userId == apCommentRepayIsLike.getUserId()){
                apCommentRepaySearchVo.setOperation(LIKE_STATUS);
            }
            commentListVos.add(apCommentRepaySearchVo);
            return null;
        }).collect(Collectors.toList());

        return ResponseResult.okResult(commentListVos);
    }

    /**
     * 评论回复点赞
     * @param likeDto
     * @return
     */
    @Override
    public ResponseResult commentRepayLike(ApCommentRepayLikeDto likeDto) {
        //判断用户是否登录
        Integer id = CommentThreadLocalUtil.getUser().getId();
        if(id == UNLOGIN_USERID){
            return ResponseResult.errorResult(AppHttpCodeEnum.USER_UNLOGIN,"用户未登录！");
        }

        ApCommentRepay apCommentRepay = mongoTemplate.findById(likeDto.getCommentRepayId(), ApCommentRepay.class);
        Integer likes = apCommentRepay.getLikes();
        //判断是点赞还是取消
        if(likeDto.getOperation() == LIKE_STATUS){
            //增加点赞数,向ApCommentIsLike表添加数据
            ApCommentRepayIsLike apCommentRepayIsLike = new ApCommentRepayIsLike();
            apCommentRepayIsLike.setUserId(id);
            apCommentRepayIsLike.setCommentRepayId(likeDto.getCommentRepayId()+"");
            mongoTemplate.save(apCommentRepayIsLike);
            //更新ApComment表的点赞数
            likes++;
            apCommentRepay.setLikes(likes);
            mongoTemplate.save(apCommentRepay);
        }else {
            //取消点赞数,在ApCommentIsLike表删除数据
            mongoTemplate.remove(Query.query(Criteria.where("commentRepayId").is(likeDto.getCommentRepayId())), ApCommentIsLike.class);
            //更新ApComment表的点赞数
            likes--;
            apCommentRepay.setLikes(likes);
            mongoTemplate.save(apCommentRepay);
        }
        return ResponseResult.okResult(likes);
    }
}
